//
//  LocationManager.m
//  Tool
//
//  Created by 周小宏 on 16/9/10.
//  Copyright © 2016年 周小宏. All rights reserved.
//

#import "LocationManager.h"

@interface LocationManager ()<AMapLocationManagerDelegate, AMapSearchDelegate>{
    CLLocation *_location;
    AMapSearchAPI *_search;
}
@end

@implementation LocationManager

+ (instancetype)sharedManager{
    static LocationManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[LocationManager alloc] init];
    });
    return manager;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        self.delegate = self;
        _search = [[AMapSearchAPI alloc] init];
        _search.delegate = self;
    }
    return self;
}

- (BOOL)isEnabledLocationServices{
    if ([CLLocationManager locationServicesEnabled] == NO) {
//        LPPZLog(@"locationServicesEnabled false");
        return NO;
    } else {
        CLAuthorizationStatus authorizationStatus= [CLLocationManager authorizationStatus];
        if(authorizationStatus == kCLAuthorizationStatusDenied || authorizationStatus == kCLAuthorizationStatusRestricted){
            return NO;
        } else {
            return YES;
        }
    }
}

- (void)getOnceLocationWithReGeocode:(completionBlock)block {
    // 带逆地理信息的一次定位（返回坐标和地址信息）
    [self setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
    //   定位超时时间，最低2s，此处设置为2s
    self.locationTimeout =3;
    //   逆地理请求超时时间，最低2s，此处设置为2s
    self.reGeocodeTimeout = 3;
    self.distanceFilter = kCLDistanceFilterNone;
    [self stopUpdatingLocation];
    [self requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
//        AMapLocationErrorLocateFailed
        block(location, regeocode, error);
    }];
}

- (void)searchPOIWithKeyWord:(NSString *)keyWord andCurrentLocation:(CLLocation *)location{
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    
    request.location            = [AMapGeoPoint locationWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
    request.keywords            = keyWord;
    /* 按照距离排序. */
    request.sortrule            = 0;
    request.offset              = 30;
    request.requireExtension    = YES;
    request.requireSubPOIs = YES;
    [_search AMapPOIAroundSearch:request];
}

- (void)searchPOIWithKeyWord:(NSString *)keyWord andAMapPolygon:(AMapGeoPolygon *)polygon {
    AMapPOIPolygonSearchRequest *request = [[AMapPOIPolygonSearchRequest alloc] init];
    request.keywords = keyWord;
    request.sortrule = 0;
    request.requireSubPOIs = YES;
    request.requireExtension = YES;
    request.polygon = polygon;
    [_search AMapPOIPolygonSearch:request];
}

- (void)searchPOIWithCity:(NSString *)city andKeyword:(NSString *)keyword {
    AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc] init];
    request.keywords            = keyword;
    request.city                = city;
    request.offset              = 30;
    request.requireExtension    = YES;
    request.cityLimit           = YES;
    request.requireSubPOIs      = YES;
    [_search AMapPOIKeywordsSearch:request];
}

- (void)getCurrentLocationReGeocode{
    [self getOnceLocationWithReGeocode:^(CLLocation *location, AMapLocationReGeocode *regeodic, NSError *error) {
        AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
        regeo.location = [AMapGeoPoint locationWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
        regeo.requireExtension = YES; 
        [_search AMapReGoecodeSearch:regeo];
    }];
}

- (void)getGeocodeWithAddress:(NSString *)address {
    [self getOnceLocationWithReGeocode:^(CLLocation *location, AMapLocationReGeocode *regeodic, NSError *error) {
        AMapGeocodeSearchRequest *geo = [[AMapGeocodeSearchRequest alloc] init];
        geo.address = address;
        [_search AMapGeocodeSearch:geo];
    }];
}

//地理编码回调
- (void)onGeocodeSearchDone:(AMapGeocodeSearchRequest *)request response:(AMapGeocodeSearchResponse *)response {
    if (self.geocode) {
        self.geocode(response,nil);
    }
}

//逆地理编码回调
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response {
    if (response.regeocode.pois.count <= 0) {
        NSError *error = [[NSError alloc] init];
        if (self.reGeocode) {
            self.reGeocode(nil, error);
        }
        return;
    }
    if (self.reGeocode) {
        self.reGeocode(response.regeocode, nil);
    }
}

//搜索回调
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response {
//    if (response.pois.count == 0)
//        {
//        return;
//    }
    NSMutableArray *poiArr = [NSMutableArray array];
    [response.pois enumerateObjectsUsingBlock:^(AMapPOI *obj, NSUInteger idx, BOOL *stop) {
        [poiArr addObject:obj.mj_keyValues];
    }];
    if (self.POIArr) {
        self.POIArr(poiArr);
    }
}

#pragma mark -- 路径规划
- (void)getPathPlanningWithOrigin:(CLLocationCoordinate2D)origin destination:(CLLocationCoordinate2D)destination {
    AMapWalkingRouteSearchRequest *navi = [[AMapWalkingRouteSearchRequest alloc] init];
    navi.origin = [AMapGeoPoint locationWithLatitude:origin.latitude longitude:origin.longitude];
    navi.destination = [AMapGeoPoint locationWithLatitude:destination.latitude longitude:destination.longitude];
    [_search AMapWalkingRouteSearch:navi];
}

- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response {
    if (response.route == nil) {
        return;
    }
    AMapPath *test = response.route.paths[0];
    if ([self.locationDelegate respondsToSelector:@selector(RouteSearchDoneResponse:)]) {
        [self.locationDelegate RouteSearchDoneResponse:response];
    }
}

#pragma mark - 行政区域
- (void)getDistrictWithKeywords:(NSString *)keywords {
    AMapDistrictSearchRequest *request = [[AMapDistrictSearchRequest alloc] init];
    request.keywords = keywords;
    [_search AMapDistrictSearch:request];
}

- (void)onDistrictSearchDone:(AMapDistrictSearchRequest *)request response:(AMapDistrictSearchResponse *)response {
    if (self.districtBlock) {
        self.districtBlock(response, nil);
    }
}

//搜索失败回调
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    if (self.reGeocode) {
        self.reGeocode(nil, error);
    }
    if (self.geocode) {
        self.geocode(nil, error);
    }
    if (self.districtBlock) {
        self.districtBlock(nil, error);
    }
}
@end
